//microcommand define zuzi
const IDC = {
  LR: "⿰", LL: "⿲", UD: "⿱", UU: "⿳",
  RD: "⿸", RU: "⿺", LD: "⿹", LU: "⿽",
  OD: "⿵", OR: "⿷", OU: "⿶", OL: "⿼", OC: "⿴",
  XX: "⿻", MI: "⿾", RO: "⿿", SU: "㇯",
}
const idcAliasPattern = Object.keys(IDC).join("|")
const idcAliasRE = new RegExp(idcAliasPattern, "ig")
const idcAliasStrictRE = new RegExp(idcAliasPattern, "g")
function isIDS(str) {
  let counter = 1
  for (const [i, c] of Object.entries([...str])) {
    if ("⿰⿱⿸⿺⿹⿽⿵⿷⿶⿼⿴⿻㇯".includes(c)) {
      counter += 1
    } else if ("⿲⿳".includes(c)) {
      counter += 2
    } else if ("⿾⿿".includes(c)) {
      // do nothing
    } else {
      if (i === 0 || --counter < 0) return false
    }
  }
  return counter === 0
}
function IDS(str) {
  const upperedConverted = str.replace(idcAliasRE, a => IDC[a.toUpperCase()])
  if (isIDS(upperedConverted)) return upperedConverted
  const strictConverted = str.replace(idcAliasStrictRE, a => IDC[a])
  if (isIDS(strictConverted)) return strictConverted
  if (isIDS(str)) return str
}
ctx.$commander.domain("zuzi-ids", content => {
  content = IDS(h.unescape(content).replace(/\s+/g, ""))
  if (!content) throw new RangeError()
  return content
}, { greedy: true })
signature("<ids:zuzi-ids>", { checkArgCount: true, strictOptions: true })
action(async ({ root, session }, ids) => {
  try {
    const buf = await ctx.http.get(`http://zu.zi.tools/${encodeURIComponent(ids)}.png`, { responseType: "arraybuffer" })
    return h.image(buf, "image/png")
  } catch (e) {
    if (e?.response?.status == 400) {
      ctx.logger.debug(e)
      const res = session.i18n(".error")
      if (root) res.unshift(h.quote(session.messageId))
      return res
    }
    throw e
  }
})
locale("zh-CN", { description: "用 zu.zi.tools 组字", usage: "支持字统网本身不支持的一些奇怪字符作为部件，如全角英文字母", messages: { error: "不支持的组字式…" } })